package com.huaxiafinance.management.util;


import com.huaxiafinance.management.mapper.*;
import com.huaxiafinance.management.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Component
public class PartnerUtil
{
    @Autowired
    private PartnerInfoMapper partnerInfoMapper;

    @Autowired
    private DistributionRuleMapper distributionRuleMapper;

    @Autowired
    private PartnerCommissionMapper partnerCommissionMapper;

    @Autowired
    private PartnerGradeMapper partnerGradeMapper;

    @Autowired
    private PartnerConditionMapper partnerConditionMapper;

    @Autowired
    private PackageOrderMapper packageOrderMapper;

    @Autowired
    private PartnerPackageMapper partnerPackageMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private MallScoreRecordMapper mallScoreRecordMapper;

    private static Integer BUYPARTNER = 19;

    public String getPartnerInviterCode()
    {
        String code;
        do
        {
            code = GiftCodeUtil.genRandomNum();
        }
        while (partnerInfoMapper.selectInviterCode(code) > 0);

        return code;
    }

    /**
     * 订单变成已支付时 提成计算
     *
     * @param orderPrice
     *            订单价格
     * @param packageType
     *            订单的类别 P Z
     * @param userUuid
     *            下单的uuid
     * @param orderNo
     *            订单号
     */
    @Transactional
    public void addMoney(BigDecimal orderPrice, String packageType, String userUuid,
                         String orderNo)
    {
        if ("Z".equalsIgnoreCase(packageType))
        {
            return;
        }
        PartnerInfo info = partnerInfoMapper.queryInfoByUserUuid(userUuid);
        // 邀请人uid
        String pUid = info.getInviterId();
        // 邀请人的邀请人id
        String ppUid = info.getInviterParentId();
        PartnerInfo pinfo = partnerInfoMapper.queryInfoByUserUuid(pUid);
        PartnerInfo ppinfo = partnerInfoMapper.queryInfoByUserUuid(ppUid);
        // 没有邀请人 或者 邀请人是准合伙人不用算提成
        if (pinfo == null)
        {
            return;
        }
        DistributionRule rule = distributionRuleMapper.getOneByGradeId(pinfo.getPartnerGradeId());
        if (rule == null)
        {
            return;
        }

        if (rule.getOneOperate() != null)
        {
            // 1级加盟商提成率
            BigDecimal oneOperate = BigDecimal.valueOf(rule.getOneOperate() / 100);
            BigDecimal getMoney = oneOperate.multiply(orderPrice);
            // 加提成
            pinfo.setRewardSum(pinfo.getRewardSum().add(getMoney));
            pinfo.setBalance(pinfo.getBalance().add(getMoney));
            // 插入提成记录
            PartnerCommission commission = new PartnerCommission();
            commission.setUserUuid(pUid);
            commission.setGmtCreate(new Date());
            commission.setAccountAmount(getMoney);
            commission.setSourceGrade(1);
            commission.setSourceType(1);
            commission.setOrderNo(orderNo);
            partnerInfoMapper.updateByPrimaryKey(pinfo);
            partnerCommissionMapper.insert(commission);
        }
        // 没有邀请人的邀请人 或者 邀请人的邀请人是准合伙人不用算提成
        if (ppinfo == null || "Z".equalsIgnoreCase(pinfo.getPartnerType()))
        {
            return;
        }
        DistributionRule rule2 = distributionRuleMapper.getOneByGradeId(
            ppinfo.getPartnerGradeId());
        if (rule2 == null)
        {
            return;
        }
        if (rule2.getTwoOperate() != null)
        {
            // 2级加盟商提成率
            BigDecimal twoOperate = BigDecimal.valueOf(rule2.getTwoOperate() / 100);
            BigDecimal getMoney = twoOperate.multiply(orderPrice);
            // 加提成
            ppinfo.setRewardSum(ppinfo.getRewardSum().add(getMoney));
            ppinfo.setBalance(ppinfo.getBalance().add(getMoney));
            // 插入提成记录
            PartnerCommission commission = new PartnerCommission();
            commission.setUserUuid(ppUid);
            commission.setGmtCreate(new Date());
            commission.setAccountAmount(getMoney);
            commission.setSourceGrade(2);
            commission.setSourceType(1);
            commission.setOrderNo(orderNo);
            partnerInfoMapper.updateByPrimaryKey(ppinfo);
            partnerCommissionMapper.insert(commission);
        }
    }

    /**
     * 升级
     *
     * @param userUuid
     *            购买套餐的人
     */
    public void upgrade(String userUuid)
    {
        PartnerInfo info = partnerInfoMapper.queryInfoByUserUuid(userUuid);
        // 邀请人uid
        String pUid = info.getInviterId();
        // 邀请人的邀请人id
        String ppUid = info.getInviterParentId();
        PartnerInfo pinfo = partnerInfoMapper.queryInfoByUserUuid(pUid);
        PartnerInfo ppinfo = partnerInfoMapper.queryInfoByUserUuid(ppUid);
        if (pinfo != null)
        {
            goUp(pinfo);
        }
        if (ppinfo != null)
        {
            goUp(ppinfo);
        }
        // 购买人是合伙人才能升级
        if (info.getIsPartner() == 1)
        {
            goUp(info);
        }
    }

    /**
     * 用户是否能升级到该等级
     *
     * @param userUuid
     * @param toGrade
     * @return boolean
     */
    public boolean isCanUpgrades(String userUuid, Integer toGrade)
    {
        boolean re = false;
        if (toGrade == null)
        {
            return false;
        }
        PartnerGrade grade = partnerGradeMapper.selectByPrimaryKey(toGrade);
        List<PartnerCondition> list = partnerConditionMapper.getListByGradeId(toGrade);
        switch (grade.getIsAllCondition())
        {
            case 1:
                for (PartnerCondition pm : list)
                {
                    if (!isSatisfyRule(pm, userUuid))
                    {
                        re = false;
                        break;
                    }
                    re = true;
                }
                break;
            case 0:
                for (PartnerCondition pm : list)
                {
                    if (isSatisfyRule(pm, userUuid))
                    {
                        re = true;
                        break;
                    }
                    re = false;
                }
                break;
            default:
                break;
        }
        return re;
    }

    /**
     * 一个规则是否满足
     *
     * @param pc
     * @param userUuid
     * @return boolean
     */
    public boolean isSatisfyRule(PartnerCondition pc, String userUuid)
    {
        boolean re = false;
        switch (pc.getPartnerType())
        {
            // 自购
            case 0:
                Integer orederNum = packageOrderMapper.countIfPayByPackageType(userUuid,
                    pc.getPackageType());
                re = orederNum >= pc.getCpurchaseNumber();
                break;
            // 一级加盟商
            case 1:
                List<String> list = partnerInfoMapper.listOnePar(userUuid);
                Integer i = 0;
                for (String uid : list)
                {
                    Integer orederNu = packageOrderMapper.countIfPayByPackageType(uid,
                        pc.getPackageType());
                    i = i + orederNu;
                }
                re = i >= pc.getCpurchaseNumber();
                break;
            // 二级加盟商
            case 2:
                List<String> lis = partnerInfoMapper.listTwoPar(userUuid);
                Integer j = 0;
                for (String uuid : lis)
                {
                    Integer num = packageOrderMapper.countIfPayByPackageType(uuid,
                        pc.getPackageType());
                    j = j + num;
                }
                re = j >= pc.getCpurchaseNumber();
                break;
            // 一级和二级
            case 3:
                List<String> l = partnerInfoMapper.listOnePar(userUuid);
                List<String> ll = partnerInfoMapper.listTwoPar(userUuid);
                l.addAll(ll);
                Integer k = 0;
                for (String d : l)
                {
                    Integer nnum = packageOrderMapper.countIfPayByPackageType(d,
                        pc.getPackageType());
                    k = k + nnum;
                }
                re = k >= pc.getCpurchaseNumber();
                break;
            default:
                break;
        }
        return re;
    }

    public Integer getNextGradeId(Integer gradeId)
    {
        Integer gradeSequence = partnerGradeMapper.selectGradeSequence(gradeId);
        Integer toGradeId = partnerGradeMapper.nextGradeId(gradeSequence, gradeId);
        return toGradeId;
    }

    public void goUp(PartnerInfo info)
    {
        Integer toGradeId = getNextGradeId(info.getPartnerGradeId());
        boolean can = isCanUpgrades(info.getUserUuid(), toGradeId);
        if (can)
        {
            info.setPartnerGradeId(toGradeId);
            partnerInfoMapper.updateByPrimaryKey(info);
        }
    }

    /**
     * 合伙人加积分
     *
     * @param pakgeId
     *            套餐id
     * @param userUuid
     *            用户id
     */
    public void addScore(Integer pakgeId, String userUuid)
    {
        MallScoreRecord record = new MallScoreRecord();
        PartnerPackage p = partnerPackageMapper.selectByPrimaryKey(pakgeId);
        MemberInfo info = memberInfoMapper.selectMemberByUserUuid(userUuid);
        if (info == null)
        {
            return;
        }
        if (p.getIsGiveScore() == 1)
        {
            // 当前积分
            info.setCurrentScore(info.getCurrentScore() + p.getSendScore());
            //添加总积分
            info.setTotalScore(info.getTotalScore()+ p.getSendScore());
            record.setUserUuid(userUuid);
            record.setModifyType(1);
            record.setScore(p.getSendScore());
            record.setTriggerId(BUYPARTNER);
            if (p.getIsSendGrowthValue() == 1)
            {
                // 成长值
                info.setGrowthValue(info.getGrowthValue() + p.getSendScore());
                record.setGrowthValue(Double.valueOf(p.getSendScore()));
            }
            else
            {
                record.setGrowthValue(0.00);
            }
            record.setGmtModified(new Date());
            memberInfoMapper.updateByPrimaryKey(info);
            mallScoreRecordMapper.insert(record);
        }
    }
}
